<!-- src/views/Register.vue -->
<template>
  <div>
    <!-- 标题栏 -->
    <mt-header title="注册">
      <mt-button icon="back" slot="left"></mt-button>
      <router-link to="/login" slot="right">
        登录
      </router-link>
    </mt-header>
    <!-- 一组文本框 -->
    <mt-field type="text" 
              placeholder="请输入用户名"
              v-model="name"
              :state="nameState"
              @blur.native.capture="checkName"
              label="用户名"></mt-field>
    <mt-field type="password" 
              placeholder="请输入密码"
              v-model="pwd"
              :state="pwdState"
              @blur.native.capture="checkPwd"
              label="密码"></mt-field>
    <mt-field type="password" 
              placeholder="请再次输入密码"
              v-model="repwd"
              :state="repwdState"
              @blur.native.capture="checkRepwd"
              label="确认密码"></mt-field>
    <mt-button type="primary" size="large" 
      @click="checkForm">
      快速注册
    </mt-button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      name: '',  // 用于与用户名做双向数据绑定
      nameState: '',
      pwd: '',   // 用于与密码框做双向数据绑定
      pwdState: '',
      repwd: '',    // 用于确认密码框的双向数据绑定
      repwdState: ''
    }
  },
  methods: {
    /** 验证重复密码 */
    checkRepwd(){
      let reg = /^\d{6}$/;
      if(reg.test(this.repwd) && this.pwd==this.repwd){
        this.repwdState = 'success';
        return true;
      }else{
        this.repwdState = 'error';
        return false;
      }
    },

    /** 验证密码 */
    checkPwd(){
      let reg = /^\d{6}$/;
      if(reg.test(this.pwd)){
        this.pwdState = 'success';
        return true;
      }else{
        this.pwdState = 'error';
        return false;
      }
    },

    /** 验证用户名 */
    checkName(){
      // 验证用户名是否符合要求
      let reg = /^\w{6,15}$/;
      if(reg.test(this.name)){  // 格式合法
        this.nameState = 'success'
        return true;
      }else{  // 格式不正确
        this.nameState = 'error'
        return false;
      }
    },

    /** 表单验证 */
    checkForm(){
      if(this.checkName() 
          && this.checkPwd() && this.checkRepwd()){
        console.log('发送请求，执行注册业务')
        // 发送post请求，传递两个参数：username  password
        this.axios.post(
          '/register', 
          `username=${this.name}&password=${this.pwd}`)
          .then(res=>{
            console.log(res);
            if(res.data.code==200){ // 注册成功
              this.$toast('注册成功');
              this.$router.push('/login');
            }else if(res.data.code==201){ // 用户已存在
              this.$toast('注册失败，用户已存在');
            }
        })
      }
    }
  },
}
</script>